package com.example.batch.config;

import com.alibaba.fastjson.JSON;
import com.example.batch.constant.JobConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Author: CHEN
 * @Date: 18/12/11 11:23
 */
@Component
@Slf4j
public class MyApplicationRunner implements ApplicationRunner {
    private final JobLauncher jobLauncher;
    private final Map<String, Job> jobMap;

    JobParameters jobParameters = new JobParametersBuilder()
            .addDate("date",new Date())
            .toJobParameters();

    @Autowired
    public MyApplicationRunner(JobLauncher jobLauncher,Map<String, Job> jobMap) {
        this.jobLauncher = jobLauncher;
        this.jobMap = jobMap;
        jobMap.entrySet().forEach(entry -> {
            log.info("job:{}",JSON.toJSONString(entry));
        });
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        startJob(jobMap.get(JobConstant.SIMPLE_JOB_DEMO));
        //startJob(jobMap.get(JobConstant.SPILT_JOB_DEMO));
        //startJob(jobMap.get(JobConstant.MULTI_FILE_JOB_DEMO));
        //startJob(jobMap.get(JobConstant.MULTI_PROCESS_JOB_DEMO));
        //startJob(jobMap.get(JobConstant.TASKLET_JOB_DEMO));

    }

    private void startJob(Job job) throws Exception {
        JobExecution execution = jobLauncher.run(job,jobParameters);
        log.info("execution",execution);
    }

}